import errorEvent from '../../errorMessage';
import store from '@/store/index'
const uuid = require('uuid');

var apis = {
    async getRenderData() {
        var projectId = store.state.mainOptions.project.projectId;
        var allFolder = `SELECT * FROM folder WHERE folder_project_id = '${projectId}' AND disable = 0 and type = 1`;
        var allApi = `SELECT doc_id,project_id, folder_id, title, status FROM project_doc WHERE project_id = '${projectId}' AND disable = 0`;
        try {
            let folderList = await window.DB.find(allFolder);
            let docList = await window.DB.find(allApi);
            for (let i = 0; i < folderList.length; i++) {
                const folderItem = folderList[i];
                folderItem.id = folderItem.folderId;
            };
            for (let i = 0; i < docList.length; i++) {
                const api = docList[i];
                api.id = api.docId;
            };
            if (folderList.length) {
                return {
                    docList: docList,
                    folderList: folderList,
                };
            } else {
                var defaultProjectFolder = `
                INSERT INTO folder (folder_id,folder_project_id,title,type,description,disable,update_time, create_time)
                VALUES('${uuid.v1()}','${projectId}','根目录',1,'根目录',0,${new Date().getTime()}, ${new Date().getTime()});`;
                await window.DB.update(defaultProjectFolder);
                var _data = await apis.getRenderData();
                return _data;
            };
        } catch (error) {
            errorEvent(error);
            return false;
        };
    },
    folder: {
        async creat(newFolder, parentFolder) {
            var _id = uuid.v1();
            var _create_time = new Date().getTime();
            var projectId = store.state.mainOptions.project.projectId;
            var sql = `INSERT INTO folder (
                    folder_id,
                    folder_project_id,
                    folder_parent_id,
                    title,
                    description,
                    type,
                    disable,
                    update_time, 
                    create_time
                    ) VALUES (
                    '${_id}',
                    '${projectId}',
                    '${parentFolder.folderId}',
                    '${newFolder.title.replace(/\'/g, "\'\'")}',
                    '${newFolder.description.replace(/\'/g, "\'\'")}',
                    1, 0,
                    ${_create_time}, 
                    ${_create_time});`;
            var _newFolderArray = [];
            if (!parentFolder.folderList) {
                parentFolder.folderList = [];
            };
            for (let i = 0; i < parentFolder.folderList.length; i++) {
                const element = parentFolder.folderList[i];
                _newFolderArray.push(element.id);
            };
            _newFolderArray.push(_id);
            // oldFolder
            var upDateFolderIndexSql = `
                    UPDATE folder SET 
                    folder_index_array = '${_newFolderArray.join(';')}',
                    update_time = ${_create_time}
                    WHERE folder_id = '${parentFolder.folderId}';`;
            try {
                await window.DB.creat(sql);
                await window.DB.update(upDateFolderIndexSql);
                return _id;
            } catch (error) {
                errorEvent(error);
                return false;
            }
        },
        async updata(updataObj, folder) {
            var time = new Date().getTime();
            var Sql = `
            UPDATE folder SET 
            title = '${updataObj.title.replace(/\'/g, "\'\'")}',
            description = '${updataObj.description.replace(/\'/g, "\'\'")}',
            update_time = ${time}
            WHERE folder_id = '${folder.id}';`;
            try {
                await window.DB.update(Sql);
                return true;
            } catch (error) {
                errorEvent(error);
                return false;
            };
        },
        async delete(Folder, Parent) {
            var time = new Date().getTime();
            var ParentFolderArray = [];
            var docIdArray = [];
            for (let i = 0; i < Parent.folderList.length; i++) {
                const element = Parent.folderList[i];
                if (element.id != Folder.id) {
                    ParentFolderArray.push(element.id);
                };
            };
            for (let i = 0; i < Folder.folderList.length; i++) {
                const element = Folder.folderList[i];
                ParentFolderArray.push(element.id);
            };
            for (let i = 0; i < Parent.docList.length; i++) {
                const element = Parent.docList[i];
                docIdArray.push(element.id);
            };
            for (let i = 0; i < Folder.docList.length; i++) {
                const element = Folder.docList[i];
                docIdArray.push(element.id);
            };

            var SqlSelf = `
            UPDATE folder SET 
            disable = 1,
            update_time = ${time}
            WHERE folder_id = '${Folder.id}';`;
            var SqlParent = `
            UPDATE folder SET 
            folder_index_array = '${ParentFolderArray.join(';')}',
            child_index_array = '${docIdArray.join(';')}',
            update_time = ${time}
            WHERE folder_id = '${Parent.id}';`;
            var Sqlfolder = `
            UPDATE folder SET
            folder_parent_id = '${Parent.id}',
            update_time = ${time}
            WHERE folder_parent_id = '${Folder.id}'; `;
            var SqlDocs = `
            UPDATE project_doc SET
            folder_id = '${Parent.id}',
            update_time = ${time}
            WHERE folder_id = '${Folder.id}'; `;
            try {
                await DB.update(SqlSelf);
                await DB.update(SqlParent);
                await DB.update(Sqlfolder);
                await DB.update(SqlDocs);
                return true;
            } catch (error) {
                errorEvent(error);
                return false;
            };
        },
        async move(type, moveType, folder, object) {
            var time = new Date().getTime();
            if (type == 'same') {
                if (moveType == 'doc') {
                    var Sql = `
                    UPDATE folder SET 
                    child_index_array = '${object.join(';')}',
                    update_time = ${time}
                    WHERE folder_id = '${folder.id}';`;
                } else if (moveType == 'folder') {
                    var Sql = `
                    UPDATE folder SET 
                    folder_index_array = '${object.join(';')}',
                    update_time = ${time}
                    WHERE folder_id = '${folder.id}';`;
                }
                try {
                    await DB.update(Sql);
                    return true;
                } catch (error) {
                    errorEvent(error);
                    return false;
                };
            } else if (type == 'different') {
                var param = folder;
                var SqlFrom = `
                UPDATE folder SET 
                ${moveType == 'doc' ? 'child_index_array' : 'folder_index_array'} = '${param.from.index}',
                update_time = ${time}
                WHERE folder_id = '${param.from.id}';`;
                var SqlTo = `
                UPDATE folder SET 
                ${moveType == 'doc' ? 'child_index_array' : 'folder_index_array'} = '${param.to.index}',
                update_time = ${time}
                WHERE folder_id = '${param.to.id}';`;
                var SqlChild = `
                UPDATE ${moveType == 'doc' ? 'project_doc' : 'folder'} SET 
                ${moveType == 'doc' ? 'folder_id' : 'folder_parent_id'} = '${param.to.id}',
                update_time = ${time}
                WHERE ${moveType == 'doc' ? 'doc_id' : 'folder_id'} = '${param.id}';`;
                try {
                    await DB.update(SqlFrom);
                    await DB.update(SqlTo);
                    await DB.update(SqlChild);
                    return true;
                } catch (error) {
                    errorEvent(error);
                    return false;
                };
            };
        },
    },
    doc: {
        // 获取详情
        async detail(id) {
            var sql = `SELECT * FROM project_doc WHERE doc_id = '${id}'`;
            try {
                let data = await window.DB.find(sql);
                return data[0].content;
            } catch (error) {
                errorEvent(error);
                return false;
            }
        },
        // 创建
        async creat(data) {
            var _id = uuid.v1();
            var projectId = store.state.mainOptions.project.projectId;
            var sql = `INSERT INTO project_doc (doc_id,folder_id,project_id,title,status,content,disable,update_time,create_time) VALUES 
            ('${_id}','${data.folderId}','${projectId}','${data.title.replace(/\'/g, "\'\'")}','${data.status}','${data.content.replace(/\'/g, "\'\'")}',0,${new Date().getTime()},${new Date().getTime()});`;
            try {
                await window.DB.update(sql);
                return _id;
            } catch (error) {
                errorEvent(error);
                return false;
            };
        },
        // 更新
        async updata(data) {
            var time = new Date().getTime();
            var Sql = `
            UPDATE project_doc SET 
            title = '${data.title.replace(/\'/g, "\'\'")}',
            content = '${data.content.replace(/\'/g, "\'\'")}',
            status = '${data.status}',
            update_time = ${time}
            WHERE doc_id = '${data.docId}';`;
            try {
                await window.DB.update(Sql);
                return true;
            } catch (error) {
                errorEvent(error);
                return false;
            };
        },
        // 删除
        async delete(id) {
            var time = new Date().getTime();
            var Sql = `
            UPDATE project_doc SET 
            disable = 1,
            update_time = ${time}
            WHERE doc_id = '${id}';`;
            try {
                await window.DB.update(Sql);
                return true;
            } catch (error) {
                errorEvent(error);
                return false;
            };
        },
        // 搜索
        async search(str) {
            var projectId = store.state.mainOptions.project.projectId;
            var sql = `
            SELECT doc_id,project_id, folder_id, title, status, update_time,create_time FROM project_doc 
            WHERE project_id = '${projectId}' 
            AND disable = 0 
            AND title LIKE '%${str.replace(/\'/g, "\'\'")}%'`;
            try {
                var docList = await DB.find(sql);
                return docList;
            } catch (error) {
                errorEvent(error);
                return false;
            };
        },
    },

};


export default apis;